<template>
  <div>
    <canvas :id='id'
            :width="width"
            :height="height"
            @click="init()"></canvas>
  </div>
</template>

<script>
import { randomColor, randomNumber } from '@/utils/random'
export default {
  name: 'graphicsCode',
  data () {
    return {

    }
  },
  props: {
    id: {
      type: String || Number,
      default: 'myCanvas'
    },
    width: {
      type: Number,
    },
    height: {
      type: Number,
      default: 50
    },
    refresh: {

      default: () => {
        return new Date().getTime()
      }
    }
  },
  watch: {
    refresh (state) {
      if (state) {
        this.init()
      }
    }
  },
  methods: {
    //初始化canvas
    init () {
      const Canvas = document.querySelector(`#${this.id}`)
      let { width, height } = Canvas;
      let num = []; //存储生成的4位随机数的集合
      let ctx = Canvas.getContext('2d');
      ctx.fillStyle = randomColor(100, 255)  //生成随机颜色
      ctx.fillRect(0, 0, width, height)
      //生成4位随机数
      for (let i = 0; i < 4; i++) {
        let x = 10 + i * 25
        let y = randomNumber(30, 40)
        ctx.font = '24px Arial'
        ctx.fillStyle = randomColor(100, 255)
        num.push(randomNumber(0, 10))
        ctx.fillText(num[i], x, y)
      }
      //生成干扰点
      for (let i = 0; i < 30; i++) {
        ctx.strokeStyle = randomColor(0, 255)
        ctx.beginPath();
        ctx.arc(randomNumber(0, width), randomNumber(0, height), 1, 0, 2 * Math.PI);
        ctx.stroke();
      }
      this.$emit('input', num.join(''))
    },
  },
  mounted () {
    this.init()
  }
}
</script>

<style>
</style>
